/*
 * @Author: Kiro AI Assistant
 * @Date: 2025-01-10
 * @Description: 锁屏状态管理器 - 处理锁屏状态变化时的信息同步
 * 
 * 功能特性：
 * 1. 监听应用生命周期变化
 * 2. 检测锁屏状态变化
 * 3. 同步音频信息到锁屏界面
 * 4. 处理后台播放状态管理
 */

import 'dart:async';
import 'package:flutter/widgets.dart';

import '../viewmodels/music_player_view_model.dart';
import 'audio_service_handler.dart';

/// 锁屏状态管理器
/// 负责处理锁屏状态变化和信息同步
class LockscreenStateManager with WidgetsBindingObserver {
  /// 单例模式
  static LockscreenStateManager? _instance;
  static LockscreenStateManager get instance {
    _instance ??= LockscreenStateManager._internal();
    return _instance!;
  }

  LockscreenStateManager._internal();

  /// 音乐播放器视图模型
  MusicPlayerViewModel? _musicPlayerViewModel;

  /// 音频服务处理器
  AudioServiceHandler? _audioServiceHandler;

  /// 应用生命周期状态
  AppLifecycleState? _currentLifecycleState;

  /// 是否已初始化
  bool _isInitialized = false;

  /// 锁屏状态变化流控制器
  final StreamController<bool> _lockscreenStateController =
      StreamController<bool>.broadcast();

  /// 锁屏状态变化流
  Stream<bool> get lockscreenStateStream => _lockscreenStateController.stream;

  /// 当前是否处于锁屏状态
  bool _isLockscreen = false;
  bool get isLockscreen => _isLockscreen;

  /// 播放器状态监听订阅
  StreamSubscription? _playerStateSubscription;

  /// 初始化锁屏状态管理器
  /// [musicPlayerViewModel] 音乐播放器视图模型
  /// [audioServiceHandler] 音频服务处理器
  Future<void> initialize({
    required MusicPlayerViewModel musicPlayerViewModel,
    required AudioServiceHandler audioServiceHandler,
  }) async {
    if (_isInitialized) return;

    _musicPlayerViewModel = musicPlayerViewModel;
    _audioServiceHandler = audioServiceHandler;

    // 注册应用生命周期观察者
    WidgetsBinding.instance.addObserver(this);

    // 监听播放器状态变化
    _setupPlayerStateListener();

    _isInitialized = true;
    debugPrint('LockscreenStateManager: 初始化完成');
  }

  /// 设置播放器状态监听器
  void _setupPlayerStateListener() {
    if (_musicPlayerViewModel == null) return;

    // 监听视图模型变化
    _musicPlayerViewModel!.addListener(_onPlayerStateChanged);

    // 监听当前播放音乐变化
    _playerStateSubscription =
        Stream.periodic(const Duration(seconds: 1)).listen((_) {
      if (_isLockscreen && _musicPlayerViewModel?.hasCurrentTrack == true) {
        _syncAudioInfoToLockscreen();
      }
    });
  }

  /// 播放器状态变化回调
  void _onPlayerStateChanged() {
    if (_isLockscreen) {
      _syncAudioInfoToLockscreen();
      _syncPlaybackStateToLockscreen();
    }
  }

  /// 应用生命周期状态变化回调
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);

    final previousState = _currentLifecycleState;
    _currentLifecycleState = state;

    debugPrint('LockscreenStateManager: 应用生命周期状态变化 $previousState -> $state');

    switch (state) {
      case AppLifecycleState.resumed:
        // 应用恢复前台
        _handleAppResumed(previousState);
        break;
      case AppLifecycleState.paused:
        // 应用进入后台
        _handleAppPaused();
        break;
      case AppLifecycleState.inactive:
        // 应用失去焦点（可能是锁屏）
        _handleAppInactive();
        break;
      case AppLifecycleState.detached:
        // 应用分离
        _handleAppDetached();
        break;
      case AppLifecycleState.hidden:
        // 应用隐藏
        _handleAppHidden();
        break;
    }
  }

  /// 处理应用恢复前台
  /// [previousState] 之前的生命周期状态
  void _handleAppResumed(AppLifecycleState? previousState) {
    // 从锁屏或后台恢复
    if (_isLockscreen || previousState == AppLifecycleState.paused) {
      _setLockscreenState(false);
      debugPrint('LockscreenStateManager: 应用从锁屏/后台恢复');
    }
  }

  /// 处理应用进入后台
  void _handleAppPaused() {
    // 可能进入锁屏状态
    _setLockscreenState(true);
    _syncAudioInfoToLockscreen();
    debugPrint('LockscreenStateManager: 应用进入后台，可能锁屏');
  }

  /// 处理应用失去焦点
  void _handleAppInactive() {
    // 应用失去焦点，可能是锁屏或其他系统界面
    debugPrint('LockscreenStateManager: 应用失去焦点');
  }

  /// 处理应用分离
  void _handleAppDetached() {
    debugPrint('LockscreenStateManager: 应用分离');
  }

  /// 处理应用隐藏
  void _handleAppHidden() {
    debugPrint('LockscreenStateManager: 应用隐藏');
  }

  /// 设置锁屏状态
  /// [isLockscreen] 是否处于锁屏状态
  void _setLockscreenState(bool isLockscreen) {
    if (_isLockscreen != isLockscreen) {
      _isLockscreen = isLockscreen;
      _lockscreenStateController.add(isLockscreen);

      if (isLockscreen) {
        _onEnterLockscreen();
      } else {
        _onExitLockscreen();
      }
    }
  }

  /// 进入锁屏状态处理
  void _onEnterLockscreen() {
    debugPrint('LockscreenStateManager: 进入锁屏状态');

    // 同步当前音频信息到锁屏界面
    _syncAudioInfoToLockscreen();

    // 确保后台播放服务正常运行
    _ensureBackgroundPlayback();
  }

  /// 退出锁屏状态处理
  void _onExitLockscreen() {
    debugPrint('LockscreenStateManager: 退出锁屏状态');

    // 可以在这里处理退出锁屏后的逻辑
    // 比如更新UI状态等
  }

  /// 同步音频信息到锁屏界面
  void _syncAudioInfoToLockscreen() {
    try {
      final currentTrack = _musicPlayerViewModel?.currentTrack;
      if (currentTrack != null && _audioServiceHandler != null) {
        // 通过AudioServiceHandler更新锁屏信息
        _audioServiceHandler!.updateLockscreenInfo();
        debugPrint('LockscreenStateManager: 音频信息已同步到锁屏界面');
      }
    } catch (error) {
      debugPrint('LockscreenStateManager: 同步音频信息失败 $error');
    }
  }

  /// 同步播放状态到锁屏界面
  void _syncPlaybackStateToLockscreen() {
    try {
      // 播放状态已通过AudioServiceHandler自动同步
      if (_audioServiceHandler != null) {
        _audioServiceHandler!.updateLockscreenInfo();
      }
      debugPrint('LockscreenStateManager: 播放状态已同步到锁屏界面');
    } catch (error) {
      debugPrint('LockscreenStateManager: 同步播放状态失败 $error');
    }
  }

  /// 确保后台播放服务正常运行
  void _ensureBackgroundPlayback() {
    try {
      // 检查当前是否有音频在播放
      final isPlaying = _musicPlayerViewModel?.isPlaying.value ?? false;
      final hasCurrentTrack = _musicPlayerViewModel?.hasCurrentTrack ?? false;

      if (isPlaying && hasCurrentTrack) {
        debugPrint('LockscreenStateManager: 后台播放服务正常运行');

        // 确保音频服务状态正确
        _audioServiceHandler?.updateLockscreenInfo();
      } else {
        debugPrint('LockscreenStateManager: 当前没有音频播放');
      }
    } catch (error) {
      debugPrint('LockscreenStateManager: 检查后台播放服务失败 $error');
    }
  }

  /// 手动触发锁屏信息同步
  /// 用于在特定情况下强制同步音频信息
  void forceSyncToLockscreen() {
    if (_isLockscreen) {
      _syncAudioInfoToLockscreen();
      _syncPlaybackStateToLockscreen();
      debugPrint('LockscreenStateManager: 手动触发锁屏信息同步');
    }
  }

  /// 检查音频焦点状态
  void checkAudioFocus() {
    try {
      final isPlaying = _musicPlayerViewModel?.isPlaying.value ?? false;
      if (isPlaying) {
        debugPrint('LockscreenStateManager: 音频焦点正常');
      } else {
        debugPrint('LockscreenStateManager: 音频已暂停');
      }
    } catch (error) {
      debugPrint('LockscreenStateManager: 检查音频焦点失败 $error');
    }
  }

  /// 处理音频焦点变化
  void handleAudioFocusChange(bool hasFocus) {
    try {
      if (hasFocus) {
        // 获得音频焦点，可以继续播放
        debugPrint('LockscreenStateManager: 获得音频焦点');
      } else {
        // 失去音频焦点，暂停播放
        debugPrint('LockscreenStateManager: 失去音频焦点');
        _musicPlayerViewModel?.pause();
      }
    } catch (error) {
      debugPrint('LockscreenStateManager: 处理音频焦点变化失败 $error');
    }
  }

  /// 释放资源
  Future<void> dispose() async {
    if (!_isInitialized) return;

    try {
      // 移除应用生命周期观察者
      WidgetsBinding.instance.removeObserver(this);

      // 移除播放器监听器
      _musicPlayerViewModel?.removeListener(_onPlayerStateChanged);

      // 取消流订阅
      await _playerStateSubscription?.cancel();

      // 关闭流控制器
      await _lockscreenStateController.close();

      _musicPlayerViewModel = null;
      _audioServiceHandler = null;
      _currentLifecycleState = null;
      _playerStateSubscription = null;
      _isInitialized = false;

      debugPrint('LockscreenStateManager: 资源已释放');
    } catch (error) {
      debugPrint('LockscreenStateManager释放资源失败: $error');
    }
  }
}
